//
//  CS_MusicDatabase.swift
//  NewSS
//
//  Created by 杨馥瑞 on 2021/9/13.
//

import Foundation
import GRDB

enum CS_MusicDatabaseError: Error {
    case identifierEmpty
    case connectionFailed
}

struct CS_MusicDatabase {
    
    private(set) var dbQueue: DatabaseQueue
    
    static private let _kDatabaseVersionStr = "v1"
    
    static private var _kIsTestEnv: Bool { kIsTestEnv }
        
    init(identifier: String) throws {
        dbQueue = try CS_MusicDatabase.setupDatabaseQueue(identifier: identifier)
        try CS_MusicDatabase.migrator.migrate(dbQueue)
    }
    
    // MARK: - 数据库的生命周期
    
    private static var migrator: DatabaseMigrator {
        var migrator = DatabaseMigrator()

        if _kIsTestEnv {
            // 当迁移有变动时重新创建数据库
            migrator.eraseDatabaseOnSchemaChange = false
        }

        /// 创建数据库
        migrator.registerMigration(_kDatabaseVersionStr) { db in
            do {
                try kInitMusicSqlArray.forEach { try db.execute(sql: $0) }
            } catch {
                print("消息 - 音乐数据库表创建失败，Error：\(error)")
            }
        }
        
        for (index, sql) in kMusicMigrationSqlList.enumerated() {
            // 创建数据库语句是 v1，migrator 从v1开始计数，index+2就是你新增的sql语句的起始位置
            migrator.registerMigration("v\(index+2)") { db in
                try db.execute(sql: sql)
            }
        }
        
        return migrator
    }
    
    /// 初始化数据库
    static func setupDatabaseQueue(identifier: String) throws -> DatabaseQueue {
        guard !identifier.isEmpty else {
            CJLog("消息 - 音乐数据库初始化失败，identifier 为空")
            throw CS_MusicDatabaseError.identifierEmpty
        }
        
        let envStr = _kIsTestEnv ? "debug" : "release"
        let databaseURL = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("\(envStr)_music_\(identifier)_\(_kDatabaseVersionStr).db.sqlite")
        
        guard let tempDbQueue = try?  DatabaseQueue(path: databaseURL.path) else {
            throw CS_MusicDatabaseError.connectionFailed
        }
        
        return tempDbQueue
    }
    
}

// MARK: - 数据库 SQL 配置语句

let kInitMusicSqlArray = [
    "PRAGMA foreign_keys = false",
    "DROP TABLE IF EXISTS music",
    """
      CREATE TABLE music (
        id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        musicTrackId VARCHAR,
        identifier VARCHAT,
        musicName VARCHAR,
        singerName VARCHAR,
        audioUrl VARCHAR,
        audioEncryptUrl VARCHAR,
        properUrlForUsed VARCHAR,
        audioLength INTEGER,
        lyricUrl VARCHAR,
        lyricType INTEGER,
        isLocal INTEGER,
        isAdded INTEGER,
        createTime INTEGER,
        modifyTime INTEGER,
        addToPlaylistTime,
        displaySingerName VARCHAR
      )
    """
]

/// 数据库升级脚本。ps: 只能在最尾部添加，不能随机插入，否则会导致重复执行旧逻辑或新添加脚本无效
let kMusicMigrationSqlList: [String] = []
